﻿using AutoMapper;
using GGGK.Film.Api.Comm;
using GGGK.Film.IService;
using GGGK.Film.Models;
using GGGK.Film.Models.Dto;
using GGGK.Film.Models.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace GGGK.Film.Api.Controllers
{
    [Route("api/[controller]")]
    public class LoginsController:ControllerBase
    {
        private readonly ILoginInfoService svc;
        private readonly IMapper mapper;

        public LoginsController(ILoginInfoService svc,IMapper mapper)
        {
            this.svc = svc;
            this.mapper = mapper;
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        [HttpPost]
        public Result Login([FromBody]LoginDto param)
        {
            var login = svc.Query(o=>o.LoginName == param.LoginName).Include(o=>o.User).FirstOrDefault();

            if (login == null)
                return new Result() { code = -1, msg = "账户不存在" };

            if (login.LoginPwd != param.LoginPwd)
                return new Result() { code = -1, msg = "密码不正确" };

            if (login.Status != 1)
                return new Result() { code = -1, msg = "用户状态异常" };

            login.LoginLastTime = DateTime.Now;
            login.LoginCount++;

            svc.Update(login);


            var token = JwtHelper.CreateJwtToken(login.User);

            return new Result() { code = 1, msg = "登录成功", data = new {token,userName=login.User.UserName,profilePhoto=login.ProfilePhoto} };
        }

    }
}
